<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.trainNo" placeholder="机车号" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        {{ $t('table.add') }}
      </el-button>
    </div>

    <div class="block block-custom">
      <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
        height="calc(85vh - 200px)">
        <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ (listQuery.page - 1) * listQuery.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="机车号" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.trainNo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="机车型号" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.trainType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车次号" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.trainNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车载部署方式" align="center" width="250">
          <template slot-scope="scope">
            <span>{{ scope.row.trainDeviceLaunch }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="车载组合" align="center" width="250">
          <template slot-scope="scope">
            <span>{{ scope.row.trainDeviceCompound }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="绑定设备" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.deviceIds.length === 0">
              无
            </div>
            <div v-else>
              <el-tag v-for="deviceId of scope.row.deviceIds" style="margin-right:15px;" type="success">
                {{ deviceId }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleEditUpdate(scope.row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button v-if="scope.row.status != 'deleted'" type="danger" @click="handleDeletedDevice(scope.row)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="onCancel">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="150px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="机车号" prop="trainNo">
          <el-input v-model="dataForm.trainNo" placeholder="请输入机车号" />
        </el-form-item>
        <el-form-item label="机车型号" prop="trainType">
          <el-input placeholder="请输入机车型号" v-model="dataForm.trainType" />
        </el-form-item>
        <el-form-item label="车次号" prop="trainNumber">
          <el-input placeholder="请输入机车型号" v-model="dataForm.trainNumber" />
        </el-form-item>
        <el-form-item label="车载部署方式" prop="trainDeviceLaunch">
          <el-select v-model="dataForm.trainDeviceLaunch" placeholder="请选择车载设备部署方式">
            <el-option v-for="item in trainDeviceLaunchOptions" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dataForm.trainDeviceLaunch == '主机+DMI' || dataForm.trainDeviceLaunch == '主机+双DMI'" label="DMI信息" prop="trainDeviceCompound">
          <el-input placeholder="请输入DMI信息" v-model="dataForm.trainDeviceCompound" />
        </el-form-item>
        <el-form-item label="绑定设备" prop="deviceId">
          <el-tag v-for="deviceId of this.dataForm.deviceIds" style="margin-right:15px;">
            {{ deviceId }}
          </el-tag>
            <el-button type="success" @click="editTrainDevice">编辑</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="设备搜索" class="view-dialog" :visible.sync="searchDeviceDialogFormVisible"
      customClass="groupDeviceDialogWidth" :show-close="false" @close="cancleDeviceList">
      <el-row :gutter="10">
        <el-col :span="16">
          <div class="filter-container">
            <el-input v-model="trainDeviceListQuery.deviceNo" placeholder="请输入设备标识号" style="width: 300px;">
              <template slot="prepend">
                设备标识号
              </template>
            </el-input>
            <el-button v-waves type="info" icon="el-icon-refresh" @click="handleResetDeviceInfo" size="small"
              style="float: right; margin-right:20px;">
              重置
            </el-button>
            <el-button v-waves type="primary" icon="el-icon-search" @click="handleSearchDeviceInfo" size="small"
              style="float: right; margin-right:20px;">
              搜索
            </el-button>
          </div>

          <el-table ref="deviceInfos" :key="tableKey" v-loading="deviceInfoListLoading" :data="deviceInfoList" fit
            highlight-current-row :header-cell-style="{ color: '#fff', backgroundColor: '#20B2AA' }"
            :row-key="handleReserveDevice" @selection-change="handleDeviceSelectionChange()" height="calc(85vh - 200px)">
            <el-table-column type="selection" align="center" width="55" reserve-selection> </el-table-column>
            <el-table-column prop="deviceName" align="center" label="设备名称" width="100"/>
            <el-table-column prop="deviceNo" align="center" label="设备标识号" width="200" />
            <el-table-column prop="manufactor" align="center" label="设备厂家" />
            <el-table-column prop="model" align="center" label="设备型号" />
            <el-table-column prop="factoryNo" align="center" label="设备出厂编号" />
          </el-table>

          <pagination v-show="deviceListTotal > 0" :total="deviceListTotal" :page.sync="trainDeviceListQuery.page" :limit.sync="trainDeviceListQuery.size" @pagination="getDeviceInfoListForPagination"
           />
        </el-col>
        <el-col :span="8">
          <div style="color: #1890ff;font-size: 16px;font-weight: bolder;padding-bottom:5px;">该群组已选{{ tagb.length }}个设备
          </div>
          <div style="height:550px;background-color:#85857ea7;padding:15px">
            <el-tag v-for="(tag, index) in tagb" :key="index" closable @close="handleDeviceCloseTag(tag)" class="active" style="font-size: 16px; padding: 5px 10px;">
              {{ tag.deviceName || tag.deviceNo || tag.deviceId }}
            </el-tag>
          </div>

          <div style="padding:10px;float:right">
            <el-button type="primary" @click="confirmDeviceList">
              确定
            </el-button>
            <el-button @click="cancleDeviceList">
              取消
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>

import { getTrainPageInfos, addOrUpdateBind, deleteDevice, createOrUpdate } from '@/api/train'
import { getInfo, getDeviceInfos } from '@/api/device'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import ElDragSelect from '@/components/DragSelect' // base on element-ui

export default {
  name: 'ComplexTable',
  components: { Pagination, ElDragSelect },
  directives: { waves },
  data() {
    return {
      tagb: [],
      trainDeviceLaunchOptions:['未部署','单主机', '主机+DMI', '主机+双DMI'],
      selectingDeviceInfo: [],
      selectedDeviceInfo: [],
      trainDeviceForm: {},
      tableKey: 0,
      list: null,
      deviceInfoList: [],
      deviceInfoListForAll: [],
      groupSelectedDevice: [],
      total: 0,
      deviceListTotal: 0,
      listLoading: false,
      deviceInfoListLoading: false,
      listQuery: {
        page: 1,
        size: 10,
        trainNo: '',
        trainType: '',
        trainNumber: '',
        trainDeviceLaunch: ''
      },
      trainDeviceListQuery: {
        deviceNo: '',
        deviceType: 1,
        deviceId: 0,
        manufactor: '',
        model: '',
        isActive: '',
        page: 1,
        size: 10
      },
      dataForm: {
        trainId: '',
        trainNo: '',
        trainType: '',
        trainNumber: '',
        trainDeviceLaunch: '',
        trainDeviceCompound: '',
        deviceIds: []
      },
      dialogFormVisible: false,
      searchDeviceDialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑修改机车信息',
        create: '新增机车'
      },
      rules: {
        trainNo: [{ required: true, message: '机车号不可空缺', trigger: 'blur' }],
        trainType: [{ required: true, message: '机车型号不可空缺', trigger: 'blur' }]
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleReserveDevice(row) {
      return row.deviceId
    },
    handleDeviceSelectionChange(index) {
      //拿到的值赋值给变量refss
      let refs = this.$refs.deviceInfos.selection
      this.tagb = this.uniqueDeviceNo(refs)
    },
    //删除已选Tag事件
    handleDeviceCloseTag(tag) {
      this.deviceInfoListForAll.forEach(row => {
        if (tag.deviceId === row.deviceId) {
          this.$refs.deviceInfos.toggleRowSelection(row, false)
        }
      })
    },

    onCancel() {
      this.dialogFormVisible = false
      this.dataForm = this.$options.data().dataForm
      this.selectedDeviceInfo = []
    },
    uniqueDeviceNo(arr) {
      // 根据唯一标识orderId来对数组进行过滤
      const res = new Map()
      //定义常量 res,值为一个Map对象实例 //返回arr数组过滤后的结果，结果为一个数组   过滤条件是，如果res中没有某个键，就设置这个键的值为1
      return arr.filter(arr => !res.has(arr.deviceId) && res.set(arr.deviceId, 1))
    },
    getList() {
      this.listLoading = true
      getTrainPageInfos(this.listQuery).then(response => {
        if (response.code === 0) {
          this.list = response.data.items
          this.total = response.data.total
          this.listLoading = false
        } else {
          this.$message.error(response.msg)
        }
      })
    },
    getDeviceInfoListForPagination() {
      this.deviceInfoListLoading = true
      if (this.trainDeviceListQuery.deviceNo === '') {
        var start = this.trainDeviceListQuery.size * (this.trainDeviceListQuery.page - 1)
        var end = this.trainDeviceListQuery.page * this.trainDeviceListQuery.size
        this.deviceInfoList = this.deviceInfoListForAll.slice(start, end)
      } else {
        this.deviceInfoList = []
        var result = this.deviceInfoListForAll.find(item => item.deviceNo === this.trainDeviceListQuery.deviceNo)
        this.deviceInfoList.push(result)
        this.deviceListTotal = this.deviceInfoList.length
      }

      this.deviceInfoListLoading = false
    },
    getDeviceInfoList() {
      this.deviceInfoListLoading = true
      // this.$refs.deviceInfos.clearSelection()
      getDeviceInfos(this.trainDeviceListQuery.deviceType).then(response => {
        if (response.code === 0) {
          this.deviceInfoListForAll = response.data
          this.deviceInfoList = this.deviceInfoListForAll
          this.deviceListTotal = this.deviceInfoList.length
          this.deviceInfoListLoading = false
          this.dataForm.deviceIds.forEach(deviceId =>{
            this.deviceInfoListForAll.forEach(row => {
              if (deviceId == row.deviceId) {                
                this.$refs.deviceInfos.toggleRowSelection(row, true)
              }
            })
          })
        } else {
          this.$message.error(response.msg)
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    calcPage() {
      let newPageing = Math.ceil((this.total - 1) / this.listQuery.size);//Math.ceil向上取整算出新的分页
      let currentPage = this.listQuery.page > newPageing ? newPageing : this.listQuery.page;//计算当前页应该是哪页
      this.listQuery.page = currentPage < 1 ? 1 : currentPage;//把当前页的值赋给this.page,重新渲染列表
    },
    handleDeletedDevice(row) {
      this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice(row.trainId).then(res => {
          if (res.code === 0) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.calcPage()
            this.getList()
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    SubmitFormData(formData) {
      createOrUpdate(formData).then(res => {
        if (res.data) {
          // let deviceIds = this.selectedDeviceInfo.map(obj=>obj.deviceId)
          this.trainDeviceForm['deviceIds'] = formData.deviceIds
          this.trainDeviceForm['trainNo'] = formData.trainNo
          addOrUpdateBind(this.trainDeviceForm).then(res=>{
            if (res.code == 0) {
              this.$message.success('机车信息提交成功')
            }
            else{
              this.$message.error(res.msg)
            }
          })
          this.getList()
          this.dialogFormVisible = false
        }
      }
      )
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.SubmitFormData(this.dataForm)
        }
      })
    },
    handleEditUpdate(row) {
      this.dataForm = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      // if (this.dataForm.deviceIds != null) {
      //   getInfo(this.dataForm.deviceId).then(res => {
      //     if (res.code == 0) {
      //       this.selectedDeviceInfo = res.data
      //     }
      //     else {
      //       this.$message.error("获取设备具体信息失败")
      //     }
      //   })
      // }
      this.dialogFormVisible = true
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.SubmitFormData(this.dataForm)
        }
      })
    },
    editTrainDevice() {
      //打开机车人员选择界面
      this.searchDeviceDialogFormVisible = true
      this.getDeviceInfoList()
    },
    handleSearchDeviceInfo() {
      this.getDeviceInfoListForPagination()
    },
    handleResetDeviceInfo() {
      this.trainDeviceListQuery.deviceNo = ''
      this.getDeviceInfoList()
    },
    confirmDeviceList() {
      //拿到的值赋值给变量refs
      let refs = this.$refs.deviceInfos.selection
      this.selectedDeviceInfo = refs
      let deviceIds = this.selectedDeviceInfo.map(obj=>obj.deviceId)
      this.dataForm.deviceIds = deviceIds
      this.$refs.deviceInfos.clearSelection()
      this.searchDeviceDialogFormVisible = false
    },
    cancleDeviceList() {
      this.selectingDeviceInfo = []
      this.$refs.deviceInfos.clearSelection()
      this.searchDeviceDialogFormVisible = false
    },
    // setCurrent(row) {
    //   this.selectingDeviceInfo = row
    //   this.$refs.deviceInfos.setCurrentRow(row);
    //   },
    // clearselectingDeviceInfo(){
    //   this.setCurrent({})
    // }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-tabs .tab-label {
  color: red;
}

.block .el-range-separator {
  width: 24px;
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px;
  /*滚动条宽度*/
  height: 8px;
  /*滚动条高度*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 0px;
  /*滚动条的背景区域的圆角*/
  background-color: rgba(2, 29, 87, 1);
  /*滚动条的背景颜色*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-corner {
  background-color: rgba(2, 29, 87, 1);
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 4px;
  /*滚动条的圆角*/
  background-color: rgba(24, 144, 255, 0.50);
  /*滚动条的背景颜色*/
}

/* .el-table__body-wrapper {
  height: calc(100% - 60px) !important;
} */

.use-name {
  font-size: 1rem;
  font-weight: 700;
  color: #606266;
}


/* 弹窗 */
/* 改变高度弹窗位置*/
/deep/ .dialog-content .el-dialog__body {
  height: 40vh;
  overflow: auto;
}

/deep/ .view-dialog>.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #FFFFFF;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #d0d0d0;
  max-height: calc(100%);
  max-width: calc(100%);
}

/deep/ .el-dialog .el-dialog__body {
  flex: 1;
  overflow: hidden auto;
  /* 隐藏水平滚动条，显示垂直滚动条 */
  /* overflow-y: scroll; 显示垂直滚动条 */
}

/deep/ .view-dialog>.el-dialog>.el-dialog__header {
  width: 100%;
  height: 54px;
  line-height: 54px;
  text-align: center;
  background: #F4F5F7;
  border-radius: 12px 12px 0px 0px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #252B3A;
  padding: 0 0 0 40px;
  padding-left: 0;
}

/deep/ .view-dialog>.el-dialog>.el-dialog__footer {
  padding-left: 0;
  padding-right: 0;
  text-align: center;
}

/deep/ .dialog-form>.el-form-item {
  margin-bottom: 30px;
}

/deep/ .dialog-form>.el-form-item>.el-form-item__content>.el-input>.el-input__inner {
  width: 220px;
  height: 34px;
  background: #FFFFFF;
  border: 1px solid #DCDEE2;
  border-radius: 3px;
}

/deep/ .dialog-form>.el-form-item>.el-form-item__content>.el-select>.el-input>.el-input__inner {
  width: 220px;
  height: 34px;
  background: #FFFFFF;
  border: 1px solid #DCDEE2;
  border-radius: 3px;
}

/deep/ .view-dialog>.el-dialog>.el-dialog__header>.el-dialog__headerbtn {
  top: 0;
}

/deep/ .view-dialog .el-form-item__content {
  width: 100%;
}
</style>

